#!/bin/sh
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: huangdi-setup-env2.sh
# author: david921518@qq.com

################
# global vars
GLB_ROOT_PART_DEV=/dev/sda2
################

let COUNTER=0
WAN_IP=$(ubus call network.interface.wan status | grep "address" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
while [ "${WAN_IP}"x == x ]; do
  sleep 1
  let COUNTER=$COUNTER+1
  if [ $COUNTER -gt 29 ]; then
    echo "Can't get WAN IP address, reboot now" 2>&1 | tee /dev/kmsg
    while true; do reboot; sleep 9; done
  fi
  WAN_IP=$(ubus call network.interface.wan status | grep "address" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
done

echo "[setup-env2] WAN IP=[${WAN_IP}]" 2>&1 | tee /dev/kmsg
sleep 1
echo "[setup-env2] PATH=[$PATH]" 2>&1 | tee /dev/kmsg
sleep 1

let COUNTER=0
while [ ! -e $GLB_ROOT_PART_DEV ]; do
  sleep 1
  let COUNTER=$COUNTER+1
  if [ $COUNTER -gt 29 ]; then
    echo "Can't find $GLB_ROOT_PART_DEV , reboot now" 2>&1 | tee /dev/kmsg
    while true; do reboot; sleep 9; done
  fi
  echo "Check $GLB_ROOT_PART_DEV again" 2>&1 | tee /dev/kmsg
done

# 1. enlarge partition
export loop_device=$(losetup -f)
loop_device=$(losetup -f)
losetup $loop_device $GLB_ROOT_PART_DEV
sleep 1
resize2fs -f $loop_device
sleep 1
df -h 2>&1 | tee /dev/kmsg
sleep 1

sync
sleep 1

echo "[setup-env2] EXIT" 2>&1 | tee /dev/kmsg
sleep 1

# restart system
#poweroff

